#include "FocusServer.h"

#include "../MouseEvent.h"
#include "Container.h"

namespace gui
{
    
FocusServer::FocusServer()
:
m_lastFocused(NULL)
{
}


FocusServer::~FocusServer()
{
    
}
 
   
    
/**
 * Resolves which component is focused after a mouse event and returns it.
 * 
 * @param event: the mouse event occurred.
 * @param root: root container that we want to check its structure for focus.
 * @return a handle to the focused component.
 */

Component* FocusServer::ResolveMouseFocus(const MouseEvent& event, gui::Container *root)
{
    int mouseX, mouseY;
    
    event.GetOccurredCoordinates( &mouseX, &mouseY );
    
    std::list< Component* >::iterator iter( root->m_components.begin( ) ), end( root->m_components.end( ) );
    
    //for each component of the root containe
    for( ; iter != end;  )
    {
	//check whether the component needs focus or not
	if( (*iter)->NeedsFocus( mouseX, mouseY ) )
	{
	    //if the component is a container
	    Container *container = (*iter)->GetContainer( );
	    
            if( container != NULL )
	    {
		//traverse the container's children
		iter = container->m_components.begin( );
		
		end = container->m_components.end( );
	    }
	    else
	    {
		Component *focused = (*iter);
		
	        if( m_lastFocused != focused )
		{
		    if( m_lastFocused )
		        m_lastFocused->Unfocus( );
		    
		    focused->Focus( );
		
		    m_lastFocused = focused;
		}
	
		return focused;
	    }
	}
	else
	{
	    ++iter;
	}
    }
    
    return NULL;
}


/**
 * @return a handle to the component that was focused last.
 */

Component* FocusServer::GetLastFocused()
{
    return m_lastFocused;
}
    
    
};